//    The page gives admin the functionality to Add / Edit Hospitals       
//    The data will be inserted/updated to the tbl_hospitals,tbl_hospital_speciality tables.                                
//    Author: Rupinder Saini                                                                    
//    Date: May 04,2006  

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;
using System.Data.SqlClient;

public partial class Admin_Ad_Hospital : System.Web.UI.Page
{

    public int id = 0;
    // creating an instance of manager class
    Manager mgr = new Manager(true,"ConnectionString");
    public DataSet ds_spe = new DataSet();
   

    protected void Page_Load(object sender, EventArgs e)
    {
        // pre-fill the dataset with the specialities available.
        ds_spe = mgr.ExecuteQuery("select Id,Name from tbl_Speciality", "tbl_Speciality");
        try
        {
            id = Convert.ToInt32(Request.QueryString["id"]);
        }
        catch 
        { id = 0; }
       
        //To show if adding or editing Hospital.
        lbl_heading.Text = id == 0 ? "Add Hospital" : "Edit Hospital";
        if (!IsPostBack)
        {
            bindgridview();
            // check page validation
            Page.Validate();
        }
    }


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
//        JSFileCreator jc = new JSFileCreator();
         check_validations();
         if (Page.IsValid)
         {
             string sql = "";
             int txtrating = 0;
             if (txt_rate.Text.Trim().Length > 0)
             {
                 if (Convert.ToInt32(Convert.ToDouble(txt_rate.Text)) > 100)
                 {
                     txtrating = 100;
                 }
                 else
                 {
                     txtrating = Convert.ToInt32(Convert.ToDouble(txt_rate.Text));
                 }
             }
             // convert the rating into Adoc Rating
             decimal dUSRating = GetADOCRating(txtrating);
             DataSet ds_id = new DataSet();
             bool duplicate;
             bool ratingvalid;
             if (id == 0) // add mode
             {  
                 //checking for duplicacy
                 sql = "select count(*) from tbl_hospitals where HName='" + txt_name.Text.Replace("'", "''").Trim() + "' and  isDelete=0 ";
                 duplicate = check_dulicate(sql);
                 ratingvalid = check_ratingvalidity();
            }
             else // edit mode
             {
                 sql = "select count(*) from tbl_hospitals where HName='" + txt_name.Text.Replace("'", "''").Trim() + "' and id<>" + id + " and  isDelete=0 ";
                 duplicate = check_dulicate(sql);
                 // check if either overall or any other rating is specified
                 ratingvalid = check_ratingvalidity();
             }

             
             if (ratingvalid == true)
             {
                 lbl_error.Visible = false;
                // if (duplicate == true)
                 {
                     lbl_error.Visible = false;
                     try
                     {
                         // add mode
                         if (id == 0)
                         {
                             SqlParameter[] sqlParam = new SqlParameter[2];
                             sqlParam[0] = new SqlParameter("@hname", SqlDbType.VarChar, 500);
                             sqlParam[1] = new SqlParameter("@rating", SqlDbType.Decimal);
                             sqlParam[1].Precision = 18;
                             sqlParam[1].Scale = 6;
                             sqlParam[0].Value = txt_name.Text;
                             sqlParam[1].Value = dUSRating;
                             ds_id = mgr.ExecuteQuery("insert_hospital", sqlParam, "tbl_hos");

                         }
                         else // update mode
                         {
                             if (duplicate == true)
                             {
                                 SqlParameter[] sqlParam = new SqlParameter[3];
                                 sqlParam[0] = new SqlParameter("@hname", SqlDbType.VarChar, 500);
                                 sqlParam[1] = new SqlParameter("@rating", SqlDbType.Decimal);
                                 sqlParam[1].Precision = 18;
                                 sqlParam[1].Scale = 6;
                                 sqlParam[2] = new SqlParameter("@id", SqlDbType.Int);
                                 sqlParam[0].Value = txt_name.Text;
                                 sqlParam[1].Value = dUSRating;
                                 sqlParam[2].Value = id;
                                 ds_id = mgr.ExecuteQuery("update_hospital", sqlParam, "tbl_hos");
                             }
                              else
                             {
                                   lbl_error.Visible = true;
                                    lbl_error.ForeColor = System.Drawing.Color.Red;
                                   lbl_error.Text = "This hospital name already exists. Please choose another name !!";
                             }
                             
                         }
                         //jc.CreateHospitalJS();
                         // checking for all the sub specialities
                         foreach (GridViewRow row in grd_spec.Rows)
                         {
                             TextBox txt = (TextBox)row.FindControl("txt_value");
                             string rate = txt.Text.ToString().Trim();
                             if (rate.Length > 0) // rating value given get the speciality id
                             {
                                 Label lbl_sp = (Label)row.FindControl("Lbl_spe");
                                 // get the speciality id
                                 DataRow[] rr = ds_spe.Tables[0].Select("Name='" + lbl_sp.Text.ToString().Trim().Replace("'", "''") + "'");
                                 int len = rr.Length;
                                // speciality id found
                                 if (len > 0)
                                 {
                                     int txtsubrating = 0;

                                     if (Convert.ToInt32(Convert.ToDouble(txt.Text)) > 100)
                                     {
                                         txtsubrating = 100;
                                     }
                                     else
                                     {
                                         txtsubrating =  Convert.ToInt32(Convert.ToDouble(txt.Text));
                                     }
                                   
                                     // get ADoc rating
                                     decimal USRating = GetADOCRating(txtsubrating);
                                     SqlParameter[] sqlParam1 = new SqlParameter[3];
                                     sqlParam1[0] = new SqlParameter("@h_id", SqlDbType.Int);
                                     sqlParam1[1] = new SqlParameter("@s_id", SqlDbType.Int);
                                     sqlParam1[2] = new SqlParameter("@score", SqlDbType.Decimal);
                                     sqlParam1[2].Precision = 18;
                                     sqlParam1[2].Scale = 6;
                                     if (id == 0) // add mode
                                     {
                                         sqlParam1[0].Value = Convert.ToInt32(ds_id.Tables[0].Rows[0]["h_id"].ToString());
                                    }
                                     else  // edit mode
                                     {
                                         sqlParam1[0].Value = id;
                                     }
                                     sqlParam1[1].Value = rr[0][0];
                                     sqlParam1[2].Value = USRating;
                                     // insert hospital specialities 
                                     try
                                     {
                                         mgr.ExecuteUpdate("insert_hospital_speciality", sqlParam1);
                                     }
                                     catch (Exception ex)
                                     {
                                         lbl_error.Visible = true;
                                         lbl_error.Text = ex.ToString();
                                         lbl_error.ForeColor = System.Drawing.Color.DarkMagenta;
                                         return;
                                     }
                                 }
                             }
                         }
                       Response.Redirect("ad_ManageHospital.aspx",true);
                     }
                     // Exception here
                     catch (Exception ex)
                     {
                         lbl_error.Visible = true;
                         lbl_error.Text = ex.ToString();
                         lbl_error.ForeColor = System.Drawing.Color.DarkMagenta;
                         return;
                     }
                 }
                // else
                 {
                   //  lbl_error.Visible = true;
                  //   lbl_error.ForeColor = System.Drawing.Color.Red;
                   //  lbl_error.Text = "This hospital name already exists. Please choose another name !!";
                 }
             }
             else
             {
                 lbl_error.Visible = true;
                 lbl_error.Text = "Either Overall or any other speciality rating must be specified";
                 lbl_error.ForeColor = System.Drawing.Color.Red;
                 return;
             }
         }

    }


    protected void btn_cancel_Click(object sender, EventArgs e)
    {
        //If Cancel button is clicked than the user will be redirected to the main page.
        if (id > 0)
            Response.Redirect("ad_ManageHospital.aspx");
        else
            Response.Redirect("ADadminAccess.aspx");

    }

    #region general functions

    /// <summary>
    /// bind the gridview
    /// </summary>
    public void bindgridview()
    {
        grd_spec.DataSource = ds_spe;
        grd_spec.DataBind();
    }

    /// <summary>
    /// check page validations
    /// </summary>
    public void check_validations()
    {
        rval_hname.Enabled = true;
        rval_hname.Validate();
    }

    /// <summary>
    /// checking for duplicate hospital name
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public bool check_dulicate(string sql)
    {
        DataSet dsname = mgr.ExecuteQuery(sql, "tbl1");
        if (dsname.Tables[0].Rows.Count > 0)
        {
            if (Convert.ToInt32(dsname.Tables[0].Rows[0][0].ToString()) > 0)
            {
                {
                   return false;
                }
            }
            else
            {
                return true;
            }
        }
        else
        {
            return true;
        }
    }



    /// <summary>
    /// To convert US rating to ADOC rating
    /// </summary>
    /// <param name="USrating"></param>
    /// <returns></returns>

    private decimal GetADOCRating(int USrating)
    {
        if (USrating.ToString().Trim().Length <= 0)
        {
            return 0;
        }
        else
        {
            // FindAdoc = (Weight - base score) * US Rating + Base Score
           return ((Convert.ToDecimal(20.00 - 13.33) * Convert.ToDecimal(USrating) / Convert.ToDecimal(100) + Convert.ToDecimal(13.33)));
        }

    }

    /// <summary>
    /// Get US Rating from the ADOC rating
    /// </summary>
    /// <param name="USrating"></param>
    /// <returns></returns>
    private decimal GetUSrating(string ADOCRating)
    {
        if (ADOCRating.Trim().Length <= 0)
        {
            return 0;
        }
        else
        {
            decimal usrating = Convert.ToDecimal((Convert.ToDouble(ADOCRating)- 13.33)*100 / (20 - 13.33));
            return (usrating);
        }

    }
  
    /// <summary>
    /// Check if either overall or any other rating is specified
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// 

    public bool check_ratingvalidity()
    {
        if (txt_rate.Text.ToString().Trim() == String.Empty) // overall rating not specified
        {
            int count = 0;
            foreach (GridViewRow row in grd_spec.Rows)
            {
                TextBox txt = (TextBox)row.FindControl("txt_value");
                string rate = txt.Text.ToString().Trim();
                if (rate.Length > 0)  // speciality specified
                {
                    return true;
                }
                else
                {
                    count = count + 1;
                }
            }
            if (count == grd_spec.Rows.Count)
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        else
        {
            return true;
        }
    }
    #endregion

    // fill the specialities offered by the hospital
    protected void grd_spec_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (id > 0)
        {
            SqlParameter[] sqlp = new SqlParameter[1];
            sqlp[0] = new SqlParameter("@id", SqlDbType.Int);
            sqlp[0].Value = id;
            DataSet ds_hosdet = mgr.ExecuteQuery("get_hospitalbyid", sqlp, "tbl");
            if (ds_hosdet.Tables[0].Rows.Count > 0)
            {
                txt_name.Text = ds_hosdet.Tables[0].Rows[0]["HName"].ToString();
                // converting to US rating that was entered by user
                decimal usrate = GetUSrating(ds_hosdet.Tables[0].Rows[0]["OverallRating"].ToString());
                if (usrate < 0)
                {
                    usrate = 0;
                }
                txt_rate.Text = usrate.ToString();
            }

            for (int j = 0; j < ds_hosdet.Tables[0].Rows.Count; j++)
            {
                DataRow[] rspe = ds_spe.Tables[0].Select("Id='" + ds_hosdet.Tables[0].Rows[j]["Speciality_Id"].ToString().Trim().Replace("'", "''") + "'");
                int rlen = rspe.Length;
                if (rlen > 0)
                {// get name of the speciality and convert the score to us rating
                    string SName = rspe[0][1].ToString();
                    decimal USSrating = GetUSrating(ds_hosdet.Tables[0].Rows[j]["Score"].ToString());
                    foreach (GridViewRow row in grd_spec.Rows)
                    {
                        Label lbl_sp = (Label)row.FindControl("Lbl_spe");
                        if (string.Compare(lbl_sp.Text, SName, true) == 0)
                        {
                            TextBox txt = (TextBox)row.FindControl("txt_value");
                            txt.Text = USSrating.ToString();
                        }
                    }

                }

            }
        }
    }
}
